package com.safety.hat.webscoket;

import com.alibaba.fastjson.JSONObject;
import com.safety.hat.config.webscoket.WebsocketEndpointConfig;
import com.safety.hat.service.admin.IAdminSocketService;
import com.safety.hat.service.admin.adpater.IAdminSocketUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author: lijun
 * @Date: 2020/5/25 0:02
 */
@Slf4j
@ServerEndpoint(value = "/adminClient", configurator = WebsocketEndpointConfig.class)
@Component
@RequiredArgsConstructor
public class AdminWebSocket {

    private final List<IAdminSocketService> adminSocketServices;
    private final IAdminSocketUserService adminSocketUserService;

    /**
     * 新建 client
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("新增连接 : {}", session);
    }

    /**
     * 关闭 client
     */
    @OnClose
    public void opClose(Session session) {
        log.info("关闭连接 : {}", session);
        adminSocketUserService.removeInfo(session);
    }

    /**
     * 发送消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (StringUtils.isNoneBlank(message)) {
            JSONObject paramObject = JSONObject.parseObject(message);
            String cmd = paramObject.getString("act");
            IAdminSocketService handleService = getHandleService(cmd);
            if (Objects.nonNull(handleService)) {
                handleService.handleMessage(handleService.transMessageToObject(message), session);
            }
        }
    }

    /**
     * 异常
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("连接异常 : {}", error);
        adminSocketUserService.removeInfo(session);
    }

    /**
     * 通过 act 获取获取当前执行逻辑
     *
     * @param act 指令
     * @return 处理service
     */
    private IAdminSocketService getHandleService(String act) {
        Optional<IAdminSocketService> serviceOptional = adminSocketServices.stream()
                .filter(service -> service.canHandle(act))
                .findAny();
        return serviceOptional.orElse(null);
    }

}       
    

